#include "stdafx.h"
#include "ckGroup.h"
#include "ckField.h"
#include "ckEnumField.h"
#include "ckEnumGroup.h"

namespace ck
{
	namespace data
	{
		Group::Group()
		{
		}


		Group::~Group()
		{
			Clear();
		}

		const char*	Group::GetName()
		{
			return m_strName.c_str();
		}

		RESULTCODE Group::SetName(const char* szName)
		{
			if (szName)
			{
				m_strName = szName;
			}
			else
			{
				m_strName.clear();
			}

			return RC_SUCCESS;
		}

		RESULTCODE Group::AddField(Field* pField)
		{
			if (pField == NULL)
			{
				return RC_FAILURE;
			}

			m_fields.push_back(pField);

			return RC_SUCCESS;
		}

		RESULTCODE Group::AddGroup(Group* pGroup)
		{
			if (pGroup == NULL)
			{
				return RC_FAILURE;
			}

			m_groups.push_back(pGroup);
			return RC_SUCCESS;
		}

		void Group::Clear()
		{
			Field* pField = NULL;
			std::vector<Field*>::iterator iter1;
			for (iter1 = m_fields.begin(); iter1 != m_fields.end(); iter1++)
			{
				pField = *iter1;
				pField->Release();
			}
			m_fields.clear();

			Group* pGroup = NULL;
			std::vector<Group*>::iterator iter2;
			for (iter2 = m_groups.begin(); iter2 != m_groups.end(); iter2++)
			{
				pGroup = *iter2;
				pGroup->Release();
			}
			m_groups.clear();
		}

		EnumGroup* Group::GetGroups()
		{
			EnumGroup* pGroups = new EnumGroup();

			Group* pGroup = NULL;
			std::vector<Group*>::iterator iter;
			for (iter = m_groups.begin(); iter != m_groups.end(); iter++)
			{
				pGroup = *iter;
				pGroup->AddRef();
				pGroups->Add(pGroup);
			}
			return pGroups;
		}

		EnumField* Group::GetFields()
		{
			EnumField* pFields = new EnumField();

			Field* pField = NULL;
			std::vector<Field*>::iterator iter;
			for (iter = m_fields.begin(); iter != m_fields.end(); iter++)
			{
				pField = *iter;
				pFields->Add(pField);
				pField->AddRef();
			}
			return pFields;
		}

		Field* Group::GetField(const char* szName)
		{
			if (szName == NULL)
			{
				return NULL;
			}

			Field* pField = NULL;
			std::vector<Field*>::iterator iter;
			for (iter = m_fields.begin(); iter != m_fields.end(); iter++)
			{
				pField = *iter;
				if (pField)
				{
					if (strcmp(pField->GetName(), szName) == 0)
					{
						return pField;
					}
				}
			}
			return NULL;
		}
	}
}

